package vn.vfriends.soffice.facade;

import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import vn.vfriends.soffice.model.Group;

/**
 *
 * @author chaungoctuan@gmail.com
 */
@Stateless
@LocalBean
public class GroupFacade extends AbstractFacade<Group> {

    @PersistenceContext(unitName = "sOfficePU")
    private EntityManager em;

    public GroupFacade() {
        super(Group.class);
    }
    
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    
    public Group findByCode(String code){
        Query query = em.createNamedQuery("Group.findByCode", Group.class);
        query.setParameter("code", code);
        List<Group> groupList = query.getResultList();
        if(groupList != null && !groupList.isEmpty())
            return groupList.get(0);
        else
            return null;
    }
    
    public Group findByName(String name){
        Query query = em.createNamedQuery("Group.findByName", Group.class);
        query.setParameter("name", name);
        List<Group> groupList = query.getResultList();
        if(groupList != null && !groupList.isEmpty())
            return groupList.get(0);
        else
            return null;
    }
    
    public List<Group> findByURL(String url){
        String jpql = "SELECT g FROM Group g LEFT JOIN g.menus m LEFT JOIN g.permissions p WHERE m.url = :url OR p.url = :url";
        Query query = em.createQuery(jpql).setParameter("url", url);
        return query.getResultList();
    }
}
